<?php

    // +----------------------------------------------------------------------
    // | 模型管理控制器
    // +----------------------------------------------------------------------
    // | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
    // +----------------------------------------------------------------------
    // | Author: 微尘 <yicmf@qq.com>
    // +----------------------------------------------------------------------

    namespace app\controller\cms\admin;

    use app\model\cms\Pattern as PatternModel;
    use yicmf\builder\Edit;
    use yicmf\builder\Table;
    use think\facade\Url;
    use app\controller\admin\Common;
    use app\model\admin\Menu;

    class Pattern extends Common
    {

        protected function initialize()
        {
            parent::initialize();
            $this->model = new PatternModel();
        }

        public function _filter()
        {
        	return [];
        }

        /**
         * 模型管理首页.
         */
        public function index()
        {
            // 显示页面
            $builder = new Table();
            $builder->model(PatternModel::class)
				->where($this->_filter())
				->suggest('网站包含的模型')
                ->searchText('title', '标题', '标题')
                ->buttonUpdate(url('cms/admin/update'))
                ->buttonAjax(url('cms/admin/Model/reset'), '重置模型配置')
                ->keyId('id', '编号', 'desc')
                ->keyText('name', '标识')
                ->keyTitle()
                ->keyUpdateTime()
                ->keyCreateTime()
                ->keyStatus()
                ->actionUpdate('update?id={$id}');

            return $builder->fetch();
        }

        public function test()
        {
            $lists = $this->model->all(['extend' => 1]);
            foreach ( $lists as $key => $data ) {
                $has = Menu::get(['url' => 'admin.Document/index?model_name=' . $data['name']]);
                if ( $has ) {
                    dump($has->getData());
                } else {
                    dump($data['name']);
                    //                 $menu = [
                    //                     'title' => $data['title'],
                    //                     'module' => 'cms',
                    //                     'pid' => Menu::where('module', 'cms')->where('title', '门户')->value('id'),
                    //                     'controller' => 'admin.Document',
                    //                     'action' => 'index?model_name=' . $data['name'],
                    //                     'url' => 'admin.Document/index?model_name=' . $data['name'],
                    //                     'hide' => 0,
                    //                     'tip' => '自动生成模型菜单',
                    //                     'icon' => isset($data['icon']) ? $data['icon'] : '',
                    //                     'group' => '模型管理'
                    //                 ];
                    //                 echo Menu::create($menu).'<br>';
                }
            }
        }

        /**
         * 新增或编辑模型.
         */
        public function update()
        {
            if ( $this->request->isPost() ) {
                if ( $this->model->updateData($this->request->post()) !== false ) {
                    $this->_returnSuccess( ($this->request->post('id') ? '更新' : '添加') . '模型成功', true);
                } else {
                    $this->_returnError( ($this->request->post('id') ? '更新' : '添加') . '模型失败，失败信息【' . $this->model->getError() . '】');
                }
            } else {
                if ( $this->request->has('id', 'get') ) {
                    /* 获取一条记录的详细数据 */
                    $data = $this->model->find($this->request->get('id'));
                    if ( !$data ) {
                        $this->_returnError( '数据不存在或者被禁用！');
                    }
                    $fields = $data->attribute ?: [];
                    // 是否继承了其他模型
                    if ( $data['extend'] != 0 ) {
                        $extend_model = $this->model->get($data['extend']);
                        $this->assign('extend_model', $extend_model);
                        $extend_fields = $extend_model->attribute ?: [];
                        $fields += $extend_fields;
                    }
                    // 梳理属性的可见性
                    foreach ( $fields as $key => $field ) {
                        if ( !empty($data['attribute_list']) && !in_array($field['id'], $data['attribute_list']) ) {
                            $fields[$key]['is_show'] = 0;
                        }
                    }
                    $this->assign('fields', $fields);
                    $this->assign('data', $data);
                    return $this->fetch();
                } else {
                    $models = $this->model->where('extend', 0)->column('title', 'id');
                    $models = array_merge([
                        '独立模型'
                    ], $models);
                    $builder = new Edit();
                    $builder->title('添加模型')
                        ->keyText('name', '模型标识', '请输入文档模型标识')
                        ->keyText('title', '模型名称', '请输入模型的名称')
                        ->keySelect('extend', '模型类型', $models, '模型类型')
                        ->keySelect('engine_type', '引擎类型', $this->model->engine_type_list, '引擎类型')
                        ->keySelect('need_pk', '是否需要主键', $this->model->need_pk_list, '选“是”则会新建默认的id字段作为主键')
                        ->data(['need_pk' => 1])
                        ->buttonClose()
                        ->buttonSubmit(url('update'), '添加');
                    return $builder->fetch();
                }
            }
        }

        /**
         * 重置模型
         */
        public function reset()
        {
            $this->_returnError( '操作失败，暂不支持删除模型');
        }

        /**
         * 删除一条数据.
         */
        public function del()
        {
            $this->_returnError( '操作失败，暂不支持删除模型');
        }
    }
